package com.vitabuybuy.tv.ui.shopcenter

import android.os.Bundle
import androidx.core.os.bundleOf
import com.blankj.utilcode.util.ScreenUtils
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityCateSearchGoodsBinding
import com.vitabuybuy.tv.dialog.GoodsScreenPopup
import com.vitabuybuy.tv.dto.*
import com.vitabuybuy.tv.ui.shopcenter.viewmodel.SearchGoodsOrStoreViewModel
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import kotlinx.android.synthetic.main.activity_cate_search_goods.*
import java.util.*

/**
 * 作者：SimGa
 * 日期：2020/12/5
 * 时间：13:36
 * 包名：com.vitabuybuy.tv.ui.shopcenter
 */
internal class CateSearchGoodsResultActivity :
    BaseActivity<SearchGoodsOrStoreViewModel, ActivityCateSearchGoodsBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true

    override val layoutId: Int
        get() = R.layout.activity_cate_search_goods

    private var cateBean: ClassificationDto.ChildrenBean.ChildrenBean2? = null
    private var pageNumber = 1
    private var sort = "featured"
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private var searchStr: String? = null
    private var storeId: Int? = null
    private var couponId: Int? = null
    private var salePriceDto = SalePriceDto()
    private var screenPopup: GoodsScreenPopup? = null
    private var areaDialog: BottomDialog? = null

    override fun onGetBundle(bundle: Bundle?) {
        super.onGetBundle(bundle)
        cateBean =
            bundle?.getSerializable("cateBean") as? ClassificationDto.ChildrenBean.ChildrenBean2
        searchStr = bundle?.getString("searchStr")
        storeId = bundle?.getInt("storeId")
        couponId = bundle?.getInt("couponId")
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(if (cateBean == null) searchStr ?: "" else cateBean?.name ?: "")
        mBinding.viewModel = viewModel
        mTabEntities.add(TabEntity(getString(R.string.recommend), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.new_product), 0, 0))
        mTabEntities.add(
            TabEntity(
                getString(R.string.price),
                R.drawable.icon_common_updown,
                R.drawable.icon_common_updown
            )
        )
        mTabLayout_1.setTabData(mTabEntities)
    }

    override fun observeData() {
        viewModel.getGoodsList(
            if (cateBean == null) searchStr!! else cateBean!!.id,
            storeId,
            couponId,
            sort,
            pageNumber
        )
        viewModel.getAllBrand()
    }

    override fun eventHandling() {
        super.eventHandling()
        refresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                super.onLoadMore(refreshLayout)
                pageNumber++
                viewModel.getGoodsList(
                    if (cateBean == null) searchStr!! else cateBean!!.id,
                    storeId,
                    couponId,
                    sort,
                    pageNumber
                )
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                super.onRefresh(refreshLayout)
                pageNumber = 1
                viewModel.getGoodsList(
                    if (cateBean == null) searchStr!! else cateBean!!.id,
                    storeId,
                    couponId,
                    sort,
                    pageNumber
                )
            }
        })
        mTabLayout_1.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                when (position) {
                    0 -> {
                        sort = "featured"
                        mTabEntities[2] =
                            TabEntity(
                                getString(R.string.price),
                                R.drawable.icon_common_updown,
                                R.drawable.icon_common_updown
                            )
                    }
                    1 -> {
                        sort = "new"
                        mTabEntities[2] =
                            TabEntity(
                                getString(R.string.price),
                                R.drawable.icon_common_updown,
                                R.drawable.icon_common_updown
                            )
                    }
                    2 -> {//点击了价格,价格从高到低
                        sort = "down_price"
                        mTabEntities[2] = TabEntity(
                            getString(R.string.price),
                            R.drawable.icon_common_updown_down,
                            R.drawable.icon_common_updown
                        )
                    }
                }
                viewModel.getGoodsList(
                    if (cateBean == null) searchStr!! else cateBean!!.id,
                    storeId,
                    couponId,
                    sort,
                    pageNumber
                )
                mTabLayout_1.setTabData(mTabEntities)
            }

            override fun onTabReselect(position: Int) {
                if (position == 2) {//一直点击价格
                    if (sort == "up_price") {//价格从高到低
                        sort = "down_price"
                        mTabEntities[2] =
                            TabEntity(
                                getString(R.string.price),
                                R.drawable.icon_common_updown_down,
                                R.drawable.icon_common_updown
                            )
                    } else if (sort == "down_price") {//从低到高是
                        sort = "up_price"
                        mTabEntities[2] =
                            TabEntity(
                                getString(R.string.price),
                                R.drawable.icon_common_updown_up,
                                R.drawable.icon_common_updown
                            )
                    }
                    pageNumber = 1
                    viewModel.getGoodsList(
                        if (cateBean == null) searchStr!! else cateBean!!.id,
                        storeId,
                        couponId,
                        sort,
                        pageNumber
                    )
                }
                mTabLayout_1.setTabData(mTabEntities)
            }
        })
        ivScreen.setOnClickListener {
            screenPopup = GoodsScreenPopup(
                mContext,
                viewModel.brandList.value!!,
                salePriceDto
            ).apply {
                setAdjustInputMethod(false)
                height = ScreenUtils.getScreenHeight()
                showPopupWindow()
            }
            screenPopup?.onConfirm = { bradList, salePrice, regionId ->
                viewModel.brandList.value = bradList
                salePriceDto = salePrice
                val brandList2 = mutableListOf<BrandDto>()
                for (brand in viewModel.brandList.value!!) {
                    if (brand.isChoose) {
                        brandList2.add(BrandDto(brand.id))
                    }
                }
                pageNumber = 1
                sort = "featured"
                mTabLayout_1.currentTab = 0
                if (brandList2.size == 0 && salePriceDto.start == 0.0 && salePriceDto.end == 0.0 && regionId == -1) {//就是没有筛选，则重新按正常搜索
                    viewModel.getGoodsList(
                        if (cateBean == null) searchStr!! else cateBean!!.id,
                        storeId,
                        couponId,
                        sort,
                        pageNumber
                    )
                } else {//否则的话，就证明有条件进行搜索
                    viewModel.getScreenGoods(
                        brandList2,
                        salePriceDto,
                        sort,
                        if (cateBean == null) searchStr!! else cateBean!!.id,
                        pageNumber, regionId
                    )
                }
            }
            screenPopup?.changeLocation = {
                //这里一定要重新创建
                areaDialog = BottomDialog(mContext, 5)
                viewModel.getRegionList(null)
            }

        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                refresh.onLoad(msg.arg1)
            }
            2 -> {
                GoodsDetailsActivity.openActivity(mContext, (msg.obj as GoodsDto).id)
            }
            3 -> {
                areaDialog!!.setDataRegion(msg.obj as MutableList<RegionDto>)
                areaDialog!!.setOnAddressSelectedListener(object : SelectedListener {
                    override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                        if (selectAbles!!.size == 1) {//表明只有国家可选
                            screenPopup?.setRegion(selectAbles[0].id, selectAbles[0].name)
                        } else {//表明有国家和下属地区
                            var area = ""
                            var regionId = -1
                            for (selectAble in selectAbles) {
                                regionId = selectAble.id
                                area = selectAble.name
                            }
                            screenPopup?.setRegion(regionId, area)
                            areaDialog = null
                        }
                    }

                    override fun onClickOnEach(selectAble: RegionDto?) {
                        viewModel.getRegionList(selectAble!!.id)
                    }
                })
                if (areaDialog!!.isShowing) return
                areaDialog!!.show()
            }
        }
    }

    companion object {
        fun openActivity(
            mContext: BaseActivity<*, *>,
            cateBean: ClassificationDto.ChildrenBean.ChildrenBean2?,
            storeId: Int?,
            couponId: Int?,
            searchStr: String?
        ) {
            mContext.startActivity(
                bundleOf(
                    Pair("cateBean", cateBean),
                    Pair("storeId", storeId),
                    Pair("couponId", couponId),
                    Pair("searchStr", searchStr)
                ),
                CateSearchGoodsResultActivity::class.java
            )
        }
    }
}